﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Security.Principal;
using System.Text;
using System.Web;
using Service.Core;
using Service.Core.Interface;
using Service.Core.Result;
using Tools;
using Web.BML.AnalysisData;
using Web.BML.CoreData;
using Web.Models.AnalysisData;
using Web.Models.CoreData;
using Web.ViewModel.CoreData;

namespace Web.Service
{
    public  class UserVesselService : BaseService
    {

        private UserVesselOp userVesselOp = UserVesselOp.GetInstance();

        private static UserVesselService instance;

        private UserVesselService()
        {

        }

        public static UserVesselService GetInstance()
        {
            if (instance == null)
            {
                instance = new UserVesselService();
            }
            return instance;
        }


        #region UserVessel DB Service

        

        /// <summary>
        /// 初始化UserVessel数据
        /// </summary>
        /// <returns></returns>
        public IServiceResult InitUserVesselData()
        {
            List<User> users = UserOp.GetInstance().QueryAllUser();
            foreach (var user in users)
            {
                foreach (var mmsi in user.MMSI.Split(','))
                {
                    AddUserVessel(mmsi, user.Id, DateTimeToStamp(DateTime.Now)+2592000*3);
                }
            }
            return Result(ResultType.Success);
        }

        /// <summary>
        /// 更新用户的所有船的信息
        /// </summary>
        /// <param name="user"></param>
        public void ModifyUserVessel(User user)
        {
            List<UserVessel> list = userVesselOp.QueryUserVessel(user.Id);
            foreach(UserVessel uservessel in list)
            {
                userVesselOp.DeleteUserVessel(uservessel);
            }
            foreach (var mmsi in user.MMSI.Split(','))
            {
                UserVessel oldModel = list.FirstOrDefault(m => m.MMSI.Equals(mmsi));
                AddUserVessel(mmsi, user.Id, oldModel == null?0:oldModel.expirationDate);
            }
        }

        /// <summary>
        /// 添加用户船舶
        /// </summary>
        /// <param name="mmsi"></param>
        /// <param name="userId"></param>
        /// <param name="expirationDate"></param>
        public void AddUserVessel(string mmsi,string userId,long expirationDate)
        {
            userVesselOp.CreateUserVessel(new UserVessel()
            {
                Id = userId+mmsi,
                MMSI = mmsi,
                expirationDate = expirationDate,
                userId = userId
            });
        }


        /// <summary>
        /// 设置公司下所有用户所有船舶的有效时间
        /// </summary>
        /// <param name="companyId"></param>
        /// <param name="datetime"></param>
        /// <returns></returns>
        public IServiceResult SetCompanyExpirationDate(String companyId,DateTime expirationDate)
        {
            if(String.IsNullOrEmpty(companyId))
            {
                return Result(ResultType.ParamIsNull,"未选中用户，请重新选择");
            }
            

            List<User> userList =  UserOp.GetInstance().QueryCompanyUser(companyId);
            if(userList.Count==0)
            {
                return Result(ResultType.ParamIsError, "操作失败，当前用户没有使用终端信息");
            }
            List<UserVessel> list = userVesselOp.QueryAllUserVessel();
            foreach (User user in userList)
            {
                if(user.Company==companyId)
                { 
                    foreach (var mmsi in user.MMSI.Split(','))
                    {
                        UserVessel userVessel = list.FirstOrDefault(m => m.MMSI.Equals(mmsi) && m.userId == user.Id);
                        userVessel.expirationDate = DateTimeHelper.ConvertDateTimeInt(expirationDate);
                        userVesselOp.ModifUserVessel(userVessel);
                    }
                }
            }
            Company company = CompanyOp.GetInstance().QueryCompany(companyId);
            company.ExpirationDate = expirationDate;
            CompanyOp.GetInstance().ModifCompany(company);
            return Result(ResultType.Success,"操作成功");
        }

        /// <summary>
        /// 设置用户所有船舶的有效时间
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="datetime"></param>
        /// <returns></returns>
        public IServiceResult SetUserExpirationDate(String userId, DateTime expirationDate)
        {
            if (String.IsNullOrEmpty(userId))
            {
                return Result(ResultType.ParamIsNull, "未选中用户，请重新选择");
            }
            List<UserVessel> userVesselList = userVesselOp.QueryUserVessel(userId);
            if (userVesselList.Count == 0)
            {
                return Result(ResultType.ParamIsError, "操作失败，当前用户没有使用对应的船舶信息或用户不存在");
            }
            
            foreach (UserVessel userVessel in userVesselList)
            {
                    userVessel.expirationDate = DateTimeHelper.ConvertDateTimeInt(expirationDate);
                    userVesselOp.ModifUserVessel(userVessel);
            }
            return Result(ResultType.Success, "操作成功");
        }


        #endregion





        // DateTime时间格式转换为Unix时间戳格式
        private int DateTimeToStamp(System.DateTime time)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            return (int)(time - startTime).TotalSeconds;
        }
    }
}